# chatload statusbar item
# shows how busy it is in chatload_channel
# credits: idea by flabber
#          script based on aki's loadavg.pl
#
# USAGE EXAMPLE:
#   1. /script load chatload.pl
#   2. /statusbar window add chatload
#   3. /set chatload_refresh  1000
#   4. /set chatload_channel  #autsider 
#
# HISTORY:
#  0.4
#      corrupted version history
#      improved USAGE EXAMPLE
#  0.3
#      better comments
#  0.2 
#      case insensitive channel name matching
#  0.1 
#      initial version
#  0.09
#      credit flabber
#
# TODO: not much. This script approaches a state of perfection.
#

use Irssi;
use vars qw($VERSION %IRSSI);
use Irssi::TextUI;
use strict;

$VERSION="0.4";
%IRSSI = (
	authors     => 'mouz',
	name        => 'chatload',
	description => 'Chatload statusbar item. Shows how busy it is in a
certain channel of choice without having to activate its window.
Gives number of lines per minute in last minute, last 5 minutes
and last 15 minutes.',
	license     => 'GNU GPLv2 or later',
);

my (@timestamps, $timeout);

sub setup {
	my $time = Irssi::settings_get_int('chatload_refresh');
	Irssi::timeout_remove($timeout);
	$timeout = Irssi::timeout_add($time, 'refresh' , undef);
}

sub refresh { 
	Irssi::statusbar_items_redraw('chatload');
}

sub show {
	my ($item, $get_size_only) = @_;
	my $avg = sprintf("%2i %.2f %.2f", averages());
	$item->default_handler($get_size_only, "{sb ".$avg."}", undef, 1);
}

sub averages {
	my $now = time();
	my $nold = grep { $_ < $now - 15*60 } @timestamps;
	foreach (1..$nold) { shift @timestamps };  # removes 'old' elements
	my $n15 = @timestamps;
	my $n05 = grep { $_ >= $now - 5*60 } @timestamps;
	my $n01 = grep { $_ >= $now - 1*60 } @timestamps;
	return ($n01, $n05/5, $n15/15);
}


sub newtext {
	my ($dest, $text, $stripped) = @_;
	return if ( Irssi::settings_get_str('chatload_channel')
	            !~ m/^$dest->{'target'}$/i );
	push @timestamps, time();
};

Irssi::statusbar_item_register('chatload', '$0', 'show');
Irssi::settings_add_int('misc', 'chatload_refresh', 1000);
Irssi::settings_add_str('misc', 'chatload_channel', '#test');
Irssi::signal_add('setup changed', 'setup');
Irssi::signal_add('print text', 'newtext');
setup();
